package main

import (
	"context"
	"time"

	pb "gitee.com/taadis/services/pubsub/proto"

	"github.com/micro/micro/v3/service"
	"github.com/micro/micro/v3/service/logger"
)

// Pub 会每秒发布一次消息
func Pub() {
	e := service.NewEvent("messages")

	for {
		err := e.Publish(context.TODO(), &pb.Message{
			Id:   "1",
			Body: []byte("hello"),
		})
		if err != nil {
			logger.Info("Error Publish:", err.Error())
		}
		time.Sleep(time.Second)
	}
}

// Sub
func Sub(ctx context.Context, msg *pb.Message) error {
	logger.Info("Received a message")
	return nil
}

func main() {
	srv := service.New(
		service.Name("pubsub"),
		service.Version("0.0.1"),
	)

	// subscribe to the "messages" topic
	service.Subscribe("messages", Sub)

	// 定时发布消息
	go Pub()

	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}
